<template>
  <div class="auth-info">
    <form @submit="save">
      <button
        class="avatar-img-wrap"
        open-type="chooseAvatar"
        @chooseavatar="setAvatar"
      >
        <img :key="form.avatar" class="avatar-img" :src="avatar" />
      </button>
      <van-field
        v-model="form.username"
        name="username"
        label="用户名"
        type="username"
        placeholder="请输入用户名"
        input-align="right"
      />

      <van-button native-type="submit" type="primary">确定</van-button>
    </form>
  </div>
</template>

<script>
import { uploadFile, updateUser } from "@/api";
import { Form, Button } from "vant";
import VanField from "@/components/VanField.jsx";
import avatarIcon from "@/assets/images/avatar-default.jpeg";

export default {
  components: {
    VanField,
    [Form.name]: Form,
    [Button.name]: Button
  },
  props: {
    data: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      form: {
        avatar: "",
        username: ""
      }
    };
  },
  computed: {
    avatar() {
      return this.form.avatar || avatarIcon;
    }
  },
  methods: {
    async setAvatar(e) {
      const { avatarUrl } = e.detail;
      if (avatarUrl) {
        const url = await uploadFile(avatarUrl);
        this.form.avatar = url;
      }
      console.log(e, "avatar");
    },
    async save(e) {
      console.log(e.detail);
      this.form.username = e.detail.value.username;
      const { avatar: headUrl, username } = this.form;
      if (!headUrl) {
        this.showMsg("请选择头像");
        return;
      }
      if (!username) {
        this.showMsg("请输入用户名");
        return;
      }
      const data = { ...this.data, ...this.form, headUrl };
      await updateUser(data);
      this.showMsg("已保存");
      setTimeout(() => {
        this.$emit("change", data);
      }, 1500);
    }
  }
};
</script>

<style lang="less">
.auth-info {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: #ffffff;

  .avatar-img-wrap {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    padding: 0;

    .avatar-img {
      width: 100%;
      height: 100%;
    }
  }

  .van-button {
    width: 200px;
  }

  .van-cell {
    font-size: 32px;
    line-height: 48px;
    padding: 30px 40px;
    color: #646566;
    margin: 60px 0;
  }

  .van-cell::after {
    left: 0;
    right: 0;
  }

  .van-cell::before {
    position: absolute;
    box-sizing: border-box;
    content: " ";
    pointer-events: none;
    top: 0;
    left: 0;
    right: 0;
    border-top: 1px solid #ebedf0;
    transform: scaleY(0.5);
  }
}
</style>
